package middlerware

import (
	"fmt"
	"gin_cli/pkg/e"
	"gin_cli/pkg/logging"
	"runtime"

	"github.com/gin-gonic/gin"
)

func Stack() []byte {
	buf := make([]byte, 1024)
	for {
		n := runtime.Stack(buf, false)
		if n < len(buf) {
			return buf[:n]
		}
		buf = make([]byte, 2*len(buf))
	}
}

func Err() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				_, file, line, _ := runtime.Caller(3)

				fmt.Printf("%T value:%v", err, err)
				method := fmt.Sprintf("Method:%v", c.Request.Method)
				errURI := fmt.Sprintf("URI:%v", c.Request.RequestURI)
				errFile := fmt.Sprintf("src:%v", file)
				errLine := fmt.Sprintf("第%d行", line)
				errBody := string(Stack())
				logging.Error(
					method,
					errURI,  // 错误的URL 请求
					errFile, // 错误的函数路径
					errLine, // 错误的函数行数
					err,     // 具体错误
					errBody,
				)
				errMsg := fmt.Sprintf("%v", err)
				c.JSON(500, e.GetResponse(e.ERROR, errMsg))
				c.Abort()
				return
			}

		}()
		c.Next()
	}
}
